﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using System.Text.RegularExpressions;

public class ParseDataHelper 
{
    static Dictionary<string, string> infoDic = new Dictionary<string, string>();
	/// <summary>
	/// 数据解析
	/// </summary>
	/// <param name="msg">内容</param>
	/// <returns>数据字典kv</returns>
	public static Dictionary<string, string> ParseDatatable(string msg)
	{
		bool isKey = false;			//key开始
		bool isValue = false;		//value开始
		bool isValueStart = false;	//是否value首次检测
		int equalIndex = 0;			// = 出现次数的计数
		int valueStartIndex = 0;	//Value的起始索引
		StringBuilder sbKey = new StringBuilder();
		StringBuilder sbvalue = new StringBuilder();
		for (int i = 0; i < msg.Length; i++)
		{
			switch (msg[i])
			{
				case '#':
					isKey = false;
					if (isValue)	//收集颜色码中的#
						sbvalue.Append(msg[i]);
					break;
				case '\r':
					continue;
				case '\n':
					isKey = true;
					isValue = false;
					if (!string.IsNullOrEmpty(sbKey.ToString()) && !string.IsNullOrEmpty(sbvalue.ToString()))
					{
						if (infoDic.ContainsKey(sbKey.ToString()))
							Debug.LogError(string.Format("[ERROR]:has the same key:{0}, value:{1}", sbKey.ToString(), sbvalue.ToString().Replace("\\n", "\n")));
						else
							infoDic.Add(sbKey.ToString(), sbvalue.ToString().Replace("\\n","\n"));
					}
					sbKey.Remove(0, sbKey.Length);
					sbvalue.Remove(0, sbvalue.Length);
					break;
				case '=':
					if (!isValue)	//忽略value里的 = 计数
						equalIndex++;
					if (equalIndex % 2 == 0 && equalIndex > 1)//key end
					{
						isKey = false;
						isValue = true;
						if (valueStartIndex != equalIndex)
						{
							isValueStart = true;
							valueStartIndex = equalIndex;
						}
					}
					if (isValue)
					{
						if (isValueStart && msg[i - 1] == '=')//忽略==value前最开始的那个=
						{
							isValueStart = false;
							continue;
						}
						sbvalue.Append(msg[i]);
					}
					break;
				default:
					if (isKey)
						sbKey.Append(msg[i]);
					else if (isValue)
					{
						if (msg[i - 1] == '\\' && msg[i + 1] == 'n')//忽略转义字符'\'
							continue;
						sbvalue.Append(msg[i]);
						DealEndLine((i == msg.Length - 1), ref infoDic, sbKey, sbvalue);
					}
					break;
			}
		}
		return infoDic;
	}

    /// <summary>
    /// 行尾特殊处理
    /// </summary>
    /// <param name="lastLine">是否最后一行</param>
    /// <param name="dictionary">infoDic</param>
    /// <param name="key">key</param>
    /// <param name="value">value</param>
    public static void DealEndLine(bool lastLine, ref Dictionary<string, string> dictionary, StringBuilder key, StringBuilder value)
    {
        if (lastLine)
        {
            if (infoDic.ContainsKey(key.ToString()))
                Debug.Log(string.Format("[ERROR]:has the same key:{0}, value:{1}", key.ToString(), value.ToString().Replace("\\n", "\n")));
            else
                infoDic.Add(key.ToString(), value.ToString().Replace("\\n", "\n"));
        }
    }

	/// <summary>
	/// 正则表达式分割字符串
	/// </summary>
	/// <param name="filePath">文件路径</param>
	/// <param name="infoDic">解析后的kv</param>
	public static void ParseDataTable(string filePath,ref Dictionary<string, string> infoDic)
	{
		infoDic.Clear();
		if (File.Exists(filePath))
		{
			using (FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read))
			{
				StreamReader sr = new StreamReader(fs);
				string data = sr.ReadLine();
				while (data != null)
				{
					if (data.StartsWith("#"))//忽略注释行
					{
						data = sr.ReadLine();
						continue;
					}
					else
					{
						//分割key和value
						string[] keyPair = Regex.Split(data,@"==",RegexOptions.IgnoreCase);
						if (keyPair.Length > 0)
						{
							if (!infoDic.ContainsKey(keyPair[0]))
							{
								infoDic.Add(keyPair[0], keyPair[1]);
							}
							else
							{
								Debug.LogError(string.Format("[ERROR]:Has same key:{0},value:{1}",keyPair[0],keyPair[1]));
							}
						}
					}
					data = sr.ReadLine();
				}
				sr.Close();
				fs.Close();
			}
		}
	}
}
